﻿namespace Baggr.Agent
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;

    public class GetFeedsForUpdate
    {
        private readonly string _ConnectionString;

        public GetFeedsForUpdate(string connectionString)
        {
            _ConnectionString = connectionString;
        }

        /// <summary>
        /// Execute command
        /// </summary>
        /// <param name="count">Count of required feeds</param>
        /// <returns>Dictionary of feed id and feed link.</returns>
        public Dictionary<Guid, string> Execute(int count)
        {
            using (var connection = new SqlConnection(_ConnectionString))
            {
                using (var command = CreateGetFeedItemsForUpdateProcedure(connection, count))
                {
                    var result = new Dictionary<Guid, string>();

                    connection.Open();
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var id = reader.GetGuid(0);
                            var link = reader.GetString(1);
                            result.Add(id, link);
                        }
                    }
                    return result;
                }
            }
        }

        /// <summary>
        /// Create procedure that recive feed id's for update.
        /// </summary>
        /// <param name="connection">Connection for command</param>
        /// <param name="count">Count of feed for update.</param>
        /// <returns>Created command</returns>
        private static SqlCommand CreateGetFeedItemsForUpdateProcedure(
            SqlConnection connection,
            int count)
        {
            var command = connection.CreateCommand();
            command.CommandText = Agent.Default.GetFeedsForUpdateProcedureName;
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue(Agent.Default.GetFeedsForUpdateProcedureCountParameterName, count);
            return command;
        }
    }
}
